<template>
  <div :class="isDialog ? '' : 'app-container invoice-mange'">
    <avue-form
      :option="queryOption"
      v-model="queryParams"
      ref="searchForm"
      v-show="showSearch"
      v-if="!isDialog"
      @keydown.enter="getList"
    >
      <template #customerId>
        <el-select
          class="w-full"
          v-model="queryParams.customerId"
          placeholder="请选择客户名称"
          @focus="selectCustomerFn('customerId')"
          clearable
          @clear="
            () => {
              queryParams.customerId = ''
            }
          "
        >
          <el-option
            v-for="item in customerOption['customerId']"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </template>
      <template #menu-form="{ size }">
        <div class="text-left p-b-2">
          <el-button
            icon="Search"
            type="primary"
            :size="size"
            @click="handleQuery"
            >查询</el-button
          >
          <el-button
            icon="Refresh"
            :size="size"
            @click="handleEmpty(searchForm)"
            >重置</el-button
          >
        </div>
      </template>
    </avue-form>

    <el-row :gutter="10" class="mb8" v-if="!isDialog">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['financial:invoiceManage:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="EditPen"
          plain
          @click="handleUpdateRow"
          :disabled="disUpdate"
          v-hasPermi="['financial:invoiceManage:edit']"
          >编辑</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Delete"
          plain
          @click="handleDelete"
          :disabled="disDelete"
          v-hasPermi="['financial:invoiceManage:dele']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Upload"
          plain
          @click="
            () => {
              uploadDia.open = true
            }
          "
          >导入</el-button
        >
      </el-col>
      <!-- <right-toolbar
        @queryTable="getList"
        v-model:showSearch="showSearch"
      ></right-toolbar> -->
    </el-row>

    <el-table
      ref="table"
      v-loading="loading"
      :data="tableList"
      row-key="id"
      stripe
      border
      :empty-text="isDialog ? '无对应可冲蓝字发票' : '暂无数据'"
      @selection-change="handleSelectionChange"
      @select-all="toggleAllSelectionFun"
      @row-click="rowClick"
    >
      <el-table-column
        type="selection"
        width="30"
        align="center"
        v-if="!isDialog || props.invoiceData.isSelection"
      />
      <el-table-column prop="orderTitle" label="关联订单" min-width="230">
        <template #default="scope">
          <el-link
            v-if="!isDialog"
            type="primary"
            :underline="false"
            @click="
              goTo('/sales/indent/salesOrderDetails', {
                salesOrderId: scope.row.orderId
              })
            "
            >{{ scope.row.orderTitle }}</el-link
          >
          <span v-else>{{ scope.row.orderTitle }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="invoiceDate" label="开票日期" width="200">
        <template #default="scope">
          <span>{{ parseTime(scope.row.invoiceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="票据类型" width="200">
        <template #default="scope">
          <dict-drop :options="invoice_manage_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="开票金额" width="150">
        <template #default="scope">
          <span>¥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="number" label="发票号码" width="200">
      </el-table-column>
      <el-table-column
        prop="content"
        label="票据内容"
        v-if="!isDialog"
        width="230"
      >
      </el-table-column>
      <el-table-column
        prop="orderBelongUserName"
        label="订单所属人员"
        width="130"
        v-if="!isDialog"
      >
      </el-table-column>
      <el-table-column
        prop="handleUserName"
        label="发票经手人员"
        width="130"
        v-if="!isDialog"
      >
      </el-table-column>
      <el-table-column
        prop="crmMsg"
        label="同步情况(CRM)"
        width="130"
        v-if="!isDialog"
      >
      </el-table-column>
      <el-table-column
        prop="invoiceMsg"
        label="同步情况(A8发票)"
        width="130"
        v-if="!isDialog"
      >
      </el-table-column>
      <el-table-column
        prop="warehouseMsg"
        label="同步情况(A8出库)"
        width="130"
        v-if="!isDialog"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        class-name="small-padding fixed-width"
        width="190"
        v-if="!props.invoiceData.isSelection"
      >
        <template #default="scope">
          <el-button
            v-if="!isDialog"
            link
            type="primary"
            icon="View"
            @click="handleDetails(scope.row)"
            >详情</el-button
          >
          <el-button
            v-if="isDialog && props.invoiceData.dialogType == '开票'"
            link
            type="primary"
            :disabled="scope.row.status !== '1' || scope.row.property !== '0'"
            icon="Postcard"
            @click="invoiceFn(scope.row)"
            >开票</el-button
          >
          <el-button
            v-if="isDialog && props.invoiceData.dialogType == '冲红'"
            link
            type="primary"
            icon="Postcard"
            @click="flushRed(scope.row)"
            >冲红</el-button
          >
          <el-dropdown v-if="!isDialog" type="primary" class="align-middle">
            <el-button link type="primary"
              >更多 <el-icon class="el-icon--right"> <arrow-down /> </el-icon
            ></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  :disabled="!(scope.row.invoiceStatus != '2')"
                  @click="handleA8Invoice(scope.row)"
                  >同步A8发票</el-dropdown-item
                >
                <el-dropdown-item
                  :disabled="scope.row.crmStatus == 1"
                  @click="handleCRMInvoice(scope.row)"
                  >同步CRM发票</el-dropdown-item
                >
                <el-dropdown-item
                  :disabled="scope.row.warehouseStatus == '2'"
                  @click="handleA8Outbound(scope.row)"
                  >同步A8出库</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    ></SelectDialog>

    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @ok="selectCustomerData"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
    ></SelectCustomer>

    <!-- 发票新增编辑表单 -->
    <el-dialog
      :title="formDialog.title"
      v-model="formDialog.open"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                v-model="formData.invoiceDate"
                type="date"
                placeholder="请输入开票日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开票金额" prop="price">
              <el-input v-model="formData.price" placeholder="请输入开票金额"
                ><template v-slot:append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开票方" prop="customerId">
              <el-select
                class="w-full"
                v-model="formData.customerId"
                placeholder="请选择开票方"
                @focus="selectCustomerFn('customerId')"
              >
                <el-option
                  v-for="item in customerOption['customerId']"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
              <!-- <el-select
                v-model="formData.customerId"
                placeholder="请选择开票方"
                class="w-full"
                filterable
                remote
                clearable
                @change="changeCustomer"
                :remote-method="queryCustomer"
                :loading="loadingSelect"
              >
                <el-option
                  v-for="item in parentOptions"
                  :key="item.id"
                  :label="item.customerName"
                  :value="item.id"
                >
                  <div>
                    <span>{{ item.customerName }}</span>
                    <span>({{ item.mainContactName }})</span>
                  </div>
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联订单" prop="orderId">
              <el-select
                class="w-full"
                suffix-icon="Search"
                remote-show-suffix
                :suffix-transition="false"
                v-model="formData.orderId"
                placeholder="请选择关联订单"
                filterable
                remote
                clearable
                @change="changeIndent"
                :remote-method="
                  val => queryIndentLimitEnt(val, formData.customerId)
                "
                :loading="loadingSelect"
              >
                <el-option
                  v-for="item in indentOptionLimitEnt"
                  :key="item.orderId"
                  :label="item.orderTitle"
                  :value="item.orderId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发票类型" prop="type">
              <el-select
                class="w-full"
                v-model="formData.type"
                placeholder="请选择发票类型"
              >
                <el-option
                  v-for="item in invoice_manage_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开票内容" prop="content">
              <el-input
                v-model="formData.content"
                placeholder="请输入开票内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发票号码" prop="number">
              <el-input
                v-model="formData.number"
                placeholder="请输入发票号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="经手人员" prop="handleUserId">
              <el-select
                class="w-full"
                v-model="formData.handleUserId"
                placeholder="请选择经手人员"
                @focus="selectUserFn('formhandleUserId')"
              >
                <el-option
                  v-for="item in userOption['formhandleUserId']"
                  :key="item.uuid"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialog.open = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </span></template
      >
    </el-dialog>

    <!-- 发票详情 -->
    <el-dialog
      :title="detailDialog.title"
      v-model="detailDialog.open"
      :close-on-click-modal="false"
      class="detailDialog"
      width="40%"
    >
      <el-descriptions title="用户信息" :column="1" border>
        <template #title>
          <TitleName
            title="基本信息"
            icon="i-carbon-bookmark-filled"
          ></TitleName>
        </template>
        <el-descriptions-item
          label="开票日期"
          label-align="right"
          label-class-name="w-40"
          >{{ formData.invoiceDate }}</el-descriptions-item
        >
        <el-descriptions-item
          label="开票金额"
          label-align="right"
          label-class-name="w-40"
          >¥{{ formData.price }}</el-descriptions-item
        >
        <el-descriptions-item label="开票方" label-align="right">{{
          formData.customerName
        }}</el-descriptions-item>
        <el-descriptions-item label="关联订单" label-align="right">{{
          formData.orderTitle
        }}</el-descriptions-item>
        <el-descriptions-item label="票据类型" label-align="right">
          <dict-drop
            :options="invoice_manage_type"
            :value="formData.type"
            :isDrop="false"
        /></el-descriptions-item>
        <el-descriptions-item label="票据内容" label-align="right">
          {{ formData.content }}
        </el-descriptions-item>
        <el-descriptions-item label="发票号码" label-align="right">{{
          formData.number
        }}</el-descriptions-item>
        <el-descriptions-item label="发票经手人员" label-align="right">{{
          formData.handleUserName
        }}</el-descriptions-item>
        <el-descriptions-item label="订单归属人员" label-align="right">{{
          formData.orderBelongUserName
        }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="系统信息" :column="1" border>
        <template #title>
          <TitleName
            title="系统信息"
            icon="i-carbon-bookmark-filled"
          ></TitleName>
        </template>
        <el-descriptions-item
          label="录入人员"
          label-align="right"
          label-class-name="w-40"
          >{{ formData.createByName }}</el-descriptions-item
        >
        <el-descriptions-item
          label="创建时间"
          label-align="right"
          label-class-name="w-40"
          >{{ formData.createTime }}</el-descriptions-item
        >
        <el-descriptions-item label="更新时间" label-align="right">{{
          formData.updateTime
        }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleUpdate(formData)">编辑记录</el-button>
          <el-button type="primary" @click="handleDelete(formData)"
            >删除记录</el-button
          >
        </span></template
      >
    </el-dialog>

    <!-- 红字开票 -->
    <el-dialog
      :title="invoicingDialog.title"
      v-model="invoicingDialog.open"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="invoicingRef"
        :model="invoicingData"
        :rules="invoicingRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="24" class="p-t-5">
            <el-form-item label="冲红原因" prop="redReason">
              <el-select
                class="w-full"
                v-model="invoicingData.redReason"
                placeholder="请选择冲红原因"
              >
                <el-option
                  v-for="item in red_reason"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="invoicingDialog.open = false">取 消</el-button>
          <el-button
            type="primary"
            @click="handleInvoicing"
            v-loading="invoicingLoading"
            >确定</el-button
          >
        </span></template
      >
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog
      :title="uploadDia.title"
      v-model="uploadDia.open"
      width="400px"
      append-to-body
      @close="closeUpload"
      :close-on-click-modal="false"
    >
      <el-upload
        v-loading="uploadLoading"
        action="#"
        :before-upload="rawFile => beforeAvatarUpload(rawFile, 'type01')"
        :http-request="params => requestFile(params, 'type01')"
        :accept="uploadType['type01'].toString()"
        :show-file-list="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div>
            <div class="el-upload__tip text-center">
              <span class="text-red"
                >仅允许导入{{ uploadType['type01'].toString() }}</span
              >
              <el-link
                type="primary"
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                @click="downUrl"
                >下载模板
              </el-link>
            </div>
            <div v-if="uploadDia.message" style="white-space: pre-line">
              导入结果：{{ uploadDia.message }}
            </div>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
          <el-button @click="closeUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="InvoiceManage">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  listInvoice,
  delInvoice,
  setInvoice,
  getInvoiceDetail,
  handleInvoice,
  importInvoice,
  handleInvoiceCrm
} from '@/api/invoiceManage/invoice'
import {
  redMakeOutInvoice,
  orderFlushRed,
  handleOutbound
} from '@/api/indentManage/indent'

import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import {
  loadingSelect, //远程检索loading
  crm_status,
  order_synchronous_status,
  companyOption, //归属公司
  indentOptionLimitEnt, // 订单数据
  queryIndentLimitEnt // 检索订单数据
} from '@/hooks/dict/order'
import { isMoneyNot } from '@/utils/validate'
import { getTreeNodeByParam, getPricipalId } from '@/utils/commo'
const userStore = useUserStore()
const props = defineProps({
  invoiceData: {
    type: Object,
    require: false,
    default: () => {
      return {
        isDialog: false
      }
    }
  },
  query: {
    type: Object,
    require: false,
    default: () => {}
  }
})
const isDialog = ref(false)

const commonStore = useCommonStore()
const route = useRoute()
const emit = defineEmits(['selectionChange'])
const router = useRouter()
const { proxy, type } = getCurrentInstance()
const { invoice_manage_type, red_reason } = proxy.useDict(
  'invoice_manage_type', //票据类型
  'red_reason' //冲红原因
)
const userOption = ref({ handleUserId: [], orderBelongUser: [] })
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: userStore.userInfo.orgId
  },
  ids: [],
  selectArr: [],
  total: 0,
  queryOption: {
    labelWidth: '10',
    menuSpan: 4,
    submitBtn: false,
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        prop: 'contractOrderNumber',
        span: 3,
        placeholder: '订单号',
        type: 'input'
      },
      {
        // label: '姓名',
        prop: 'type',
        span: 3,
        placeholder: '票据类型',
        type: 'select',
        dicData: invoice_manage_type
      },
      {
        prop: 'invoiceDate',
        type: 'daterange',
        span: 4,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '开票开始时间',
        endPlaceholder: '开票结束时间'
      },
      {
        prop: '_handleUserId',
        span: 3,
        placeholder: '发票经手人',
        type: 'select',
        clearable: false,
        props: {
          value: 'uuid'
        },
        popperClass: 'className',
        dicData: computed(() => {
          return userOption.value['handleUserId']
        }),
        multiple: true,
        click: ({ value, column }) => {
          dialogParam.value.type = 'handleUserId'
          dialogParam.value.title = '请选择发票经手人'
          dialogParam.value.isDialog = true
          dialogParam.value.multiple = false
          dialogParam.value.nodeKey = 'uuid'
          dialogParam.value.defaultCheckedKeys = queryParams.value._handleUserId
          dialogParam.value.dataType = 'person'
        }
      },
      {
        prop: '_orderBelongUser',
        span: 3,
        placeholder: '订单所属人员',
        type: 'select',
        clearable: false,
        props: {
          value: 'uuid'
        },
        popperClass: 'className',
        dicData: [], //userOption.value['orderBelongUser'],
        multiple: true,
        change: ({ value, column }) => {
          // console.log('column==>', column)
          column.dicData = userOption.value['orderBelongUser']
        },
        click: ({ value, column }) => {
          dialogParam.value.type = 'orderBelongUser'
          dialogParam.value.title = '请选择订单所属人员'
          dialogParam.value.isDialog = true
          dialogParam.value.multiple = false
          dialogParam.value.nodeKey = 'uuid'
          dialogParam.value.defaultCheckedKeys =
            queryParams.value._orderBelongUser
          dialogParam.value.dataType = 'person'
        }
      },
      {
        prop: 'deptId',
        span: 3,
        placeholder: '所属公司',
        type: 'tree',
        defaultExpandAll: true,
        disabled: userStore.userInfo.orgId != 484,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption
      },
      // {
      //   span: 3,
      //   prop: 'customerId',
      //   placeholder: '客户名称'
      // },
      {
        span: 4,
        prop: 'customerName',
        placeholder: '客户名称',
        type: 'input'
      },
      {
        span: 3,
        prop: 'number',
        placeholder: '发票号码'
      },
      {
        span: 2,
        prop: 'crmStatus',
        placeholder: 'crm同步状态',
        type: 'tree',
        dicData: crm_status
      },
      {
        span: 2,
        prop: 'invoiceStatus',
        placeholder: '发票同步情况',
        type: 'tree',
        dicData: order_synchronous_status
      },
      {
        span: 2,
        prop: 'warehouseStatus',
        placeholder: '出库同步情况',
        type: 'tree',
        dicData: order_synchronous_status
      }
      // {
      //   prop: 'orderBelongDept',
      //   span: 3,
      //   placeholder: '订单所属部门',
      //   type: 'tree',
      //   props: {
      //     value: 'deptId',
      //     label: 'deptName'
      //   },
      //   dicData: []
      // },
    ]
  },
  showSearch: true,
  searchDrawer: false /* 高级检索框 */,
  disUpdate: true /* 编辑按钮是否可编辑 */,
  disDelete: true /* 关闭按钮是否可编辑 */,
  loading: false,
  tableList: [],
  dialogParam: {} /* 人员弹窗框参数 */,
  customerOption: {}, //客户选择下拉
  dialogParamA: {} /* 客户弹窗框参数 */,
  formData: {
    customerType: 'customer' //客户类型
  },
  formRules: {
    invoiceDate: [
      {
        required: true,
        message: '请选择开票日期',
        trigger: 'change'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入开票金额',
        trigger: 'blur'
      },
      {
        validator: isMoneyNot
      }
    ],
    customerId: [
      {
        required: true,
        message: '请选择开票方',
        trigger: 'change'
      }
    ],
    orderId: [
      {
        required: true,
        message: '请选择关联订单',
        trigger: 'change'
      }
    ],
    type: [
      {
        required: true,
        message: '请选择发票类型',
        trigger: 'change'
      }
    ],
    content: [
      {
        required: true,
        message: '请选择开票内容',
        trigger: 'blur'
      }
    ],
    number: [
      {
        required: true,
        message: '请选择发票号',
        trigger: 'blur'
      }
    ],
    handleUserId: [
      {
        required: true,
        message: '请选择经手人员',
        trigger: 'change'
      }
    ]
  },
  formDialog: {
    title: '新增',
    open: false
  },
  detailDialog: {
    title: '详情',
    open: false
  }
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  queryOption,
  showSearch,
  searchDrawer,
  disUpdate,
  disDelete,
  loading,
  tableList,
  dialogParam,
  customerOption,
  dialogParamA,
  formData,
  formRules,
  formDialog,
  detailDialog
} = toRefs(data)

// watch(
//   () => formData.value.customerId,
//   val => {
//     changeCustomer(formData.value.customerId)
//   },
//   { deep: true }
// )
// watchEffect(() => {
//   if (route.query.invoiceData && route.name == type.name) {
//     let invoiceData = JSON.parse(route.query.invoiceData)
//     if (invoiceData.type == 'add') {
//       handleAdd()
//     }
//     if (invoiceData.type == 'detail') {
//       detailDialog.value.open = true
//       getFormData(invoiceData.id)
//     }
//   }
// })

// 提交
function handleQuery() {
  getList()
}
// 重置
function handleEmpty(formEl) {
  proxy.$refs.searchForm.resetForm()
  getList()
}
const toggleAllSelectionFun = value => {
  if (isDialog.value && !props.invoiceData?.multiple) {
    proxy.$refs.table.clearSelection()
  }
}
// 初始化
async function init() {
  console.log('props==>', props.invoiceData)
  isDialog.value = props.invoiceData.isDialog
  queryParams.value = { ...queryParams.value, ...props.query }
  // 获取参数
  if (route.query.invoiceData && route.name == type.name) {
    let invoiceData = JSON.parse(route.query.invoiceData)
    if (invoiceData.type == 'add') {
      handleAdd()
    }
    if (invoiceData.type == 'detail') {
      detailDialog.value.open = true
      getFormData(invoiceData.id)
    }
  }

  getList()
}
// 获取数据列表
function getList() {
  loading.value = true

  // 发票经手人
  queryParams.value.handleUserId = getPricipalId(
    userOption.value['handleUserId'],
    queryParams.value._handleUserId
  )
  // 订单所属人
  queryParams.value.orderBelongUser = getPricipalId(
    userOption.value['orderBelongUser'],
    queryParams.value._orderBelongUser
  )
  listInvoice(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    console.log(' tableList.value==>', tableList.value)
  })
  console.log('获取数据')
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDelete.value = !selection.length
  emit('selectionChange', selectArr.value)
}
// 单击行
function rowClick(row, column, event) {
  if (!isDialog.value) return
  // 根据id判断当前点击的是否被选中
  const selected = selectArr.value.some(item => item.id === row.id)
  if (!selected) {
    if (props.invoiceData?.multiple) {
      // 选择
      selectArr.value.push(row)
    } else {
      toggleAllSelectionFun()
      selectArr.value = [row]
    }
    proxy.$refs.table.toggleRowSelection(row, true)
  } else {
    // 取消
    var finalArr = selectArr.value.filter(item => {
      return item.id !== row.id
    })
    // 取消后剩余选中的
    selectArr.value = finalArr
    proxy.$refs.table.toggleRowSelection(row, false)
  }
}

function goTo(url, data) {
  router.push({ path: url, query: data })
}
// 新增
function handleAdd() {
  goTo('/financial/invoiceForm')
  // reset()
  // formDialog.value.open = true
  // formDialog.value.title = '新增'
}
// 编辑
function handleUpdate() {
  goTo('/financial/editInvoice', { invoiceId: ids.value[0] })
  // detailDialog.value.open = false
  // formDialog.value.open = true
  // formDialog.value.title = '编辑'
}
// 编辑
function handleUpdateRow() {
  goTo('/financial/editInvoice', { invoiceId: ids.value[0] })
  // formDialog.value.open = true
  // formDialog.value.title = '编辑'
  // let id = ids.value[0]
  // getFormData(id)
}
// 详情
function handleDetails(row) {
  goTo('/financial/invoiceDetails', { invoiceId: row.id })
  // detailDialog.value.open = true
  // getFormData(row.id)
}
// 删除
function handleDelete(row) {
  let rowIds = row.id || ids.value
  // console.log('selectArr-->', selectArr.value, 'id==>', rowIds)
  proxy.$modal
    .confirm('是否删除该票据')
    .then(function () {
      let data = {
        ids: rowIds,
        type: 'invoice'
      }
      return delInvoice(data)
    })
    .then(() => {
      getList()
      detailDialog.value.open = false
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName) {
  switch (keyName) {
    case 'customerId':
      dialogParamA.value.type = keyName
      dialogParamA.value.tabVal = 'customer'
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      // dialogParamA.value.defaultCheckedKeys = formData.value[keyName]
      // dialogParamA.value.defaultCheckedLabel = formData.value['customerName']
      dialogParamA.value.dataType = 'person'
      break
  }
}

// 客户选择选择确定
const selectCustomerData = val => {
  switch (val.type) {
    case 'customerId':
      customerOption.value.customerId = val.selectData
      queryParams.value.customerId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
  }
}

// 改变客户名称后
const changeCustomer = val => {
  // formData.value.customerName = obj[0].customerName
  formData.value.orderId = null
  queryIndentLimitEnt(undefined, formData.value.customerId)
}
// 订单赋值
function changeIndent(row) {
  console.log('row==>', row)
}
/* 人员选择
 * @param {string}
 */
function selectUserFn(keyName) {
  dialogParam.value.type = keyName
  dialogParam.value.title = '经手人员'
  dialogParam.value.isDialog = true
  dialogParam.value.multiple = false
  dialogParam.value.nodeKey = 'uuid'
  dialogParam.value.defaultCheckedKeys = [formData.value[keyName]]
  dialogParam.value.dataType = 'person'
}
// 人员id转uuid
async function getDefaultUserInfo(val, fieldName, selectArr) {
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  } else {
    return
  }
  //获取部门人员数据
  const deptUserData = await commonStore.getUseTreeData()
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(deptUserData, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      formData.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}
/* 人员确认 */
const selectDialogData = val => {
  switch (val.type) {
    case 'handleUserId':
      userOption.value.handleUserId = val.selectData
      // queryOption.value.column[2].dicData = val.selectData
      queryParams.value._handleUserId = val.defaultCheckedKeys
      break
    case 'formhandleUserId':
      userOption.value.formhandleUserId = val.selectData
      formData.value.handleUserId = val.defaultCheckedKeys.toString()
      break
    case 'orderBelongUser':
      userOption.value.orderBelongUser = val.selectData
      queryParams.value._orderBelongUser = val.defaultCheckedKeys
      break
  }
}

// 保存
function handleSubmit(e) {
  console.log('保存-<>', formData.value)
  proxy.$refs.formRef.validate((valid, msg) => {
    if (valid) {
      formData.value.handleUserId = getPricipalId(
        userOption.value['formhandleUserId'],
        formData.value.handleUserId
      ).toString()
      setInvoice(formData.value).then(res => {
        proxy.$modal.msgSuccess(formData.value.id ? '修改成功' : '新增成功')
        getFormData(res.data.id)

        formDialog.value.open = false
        getList()
        // formDialog.value.title = formData.value.id ? '编辑' : '新增'
      })
    }
  })
}
// 获取表单数据
function getFormData(id) {
  getInvoiceDetail(id).then(async res => {
    let resData = {}
    resData = res.data
    customerOption.value['customerId'] = [
      {
        label: resData.customerName, //? resData.customerName: resData.customerId,
        id: resData.customerId //? resData.customerId : resData.customerName
      }
    ]
    indentOptionLimitEnt.value = [
      {
        orderTitle: resData.orderTitle, //? resData.customerName: resData.customerId,
        orderId: resData.orderId //? resData.customerId : resData.customerName
      }
    ]
    formData.value = resData
    // 经手人员
    await getDefaultUserInfo(
      formData.value.handleUserId,
      'handleUserId',
      'formhandleUserId'
    )
  })
}

/** 表单重置 */
function reset() {
  formData.value = {}
  proxy.resetForm('formRef')
}

// 冲红表单
const invoicingData = ref({})
const invoicingRules = ref({
  redReason: [
    {
      required: true,
      message: '请选择冲红原因',
      trigger: 'change'
    }
  ]
})
// 开票弹窗
const invoicingDialog = ref({
  open: false,
  title: '红字开票'
})
// 点击开票按钮
const invoiceFn = async row => {
  invoicingDialog.value.open = true
  invoicingData.value.invoiceNumber = row.number
  invoicingData.value.orderId = row.oppositeId
}
// 点击冲红按钮
const flushRed = async row => {
  if (row.sameInvoiceMsg) {
    proxy
      .$confirm(row.sameInvoiceMsg, '提示', {
        confirmButtonText: '冲红',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        await redInvoice(row)
      })
      .catch(() => {
        return
      })
  } else {
    redInvoice(row)
  }
}
// 冲红请求
const redInvoice = async data => {
  let res = await orderFlushRed({
    invoiceNumber: data.number,
    orderId: data.orderId
  })
  if (res.code !== 200) return
  goTo('/sales/indent/editSalesOrder', { salesOrderId: res.data.id })
}
const invoicingLoading = ref(false)
const handleInvoicing = () => {
  invoicingLoading.value = true
  proxy.$refs.invoicingRef.validate(async (valid, msg) => {
    if (valid) {
      try {
        let res = await redMakeOutInvoice(invoicingData.value)
        if (res.code == 200) {
          invoicingDialog.value.open = false
          proxy.$modal.msgSuccess('提交成功')
          getList()
        }
        invoicingLoading.value = false
      } catch (error) {
        invoicingLoading.value = false
      }
    } else {
      invoicingLoading.value = false
    }
  })
}

// 同步a8发票
const handleA8Invoice = row => {
  handleInvoice(row.id).then(res => {
    proxy.$modal.msgSuccess('同步成功')
    getList()
  })
}
// 同步CRM发票
const handleCRMInvoice = row => {
  handleInvoiceCrm(row.id).then(res => {
    proxy.$modal.msgSuccess('同步成功')
    getList()
  })
}
// 同步A8出库
const handleA8Outbound = row => {
  handleOutbound(row.orderId).then(res => {
    proxy.$modal.msgSuccess('同步成功')
    getList()
  })
}

/* 数据导入 开始 */
// 导入弹窗
const uploadDia = ref({
  title: '导入发票',
  open: false,
  message: ''
})
const uploadType = {
  type01: ['.xls', '.xlsx'],
  type02: [
    '.rar',
    '.zip',
    '.doc',
    '.docx',
    '.pdf',
    '.xls',
    '.xlsx',
    '.ppt',
    '.pptx',
    '.gif',
    '.jpg',
    '.jpeg',
    '.png'
  ]
}
// 模板下载
const downUrl = async function downUrl() {
  const url = await commonStore.getUploadTemplateDown('invoice_import_template')
  // console.info('url', url)
  window.open(url, '_blank')
}
/**导入数据 限制条件
 *
 * @param {*} rawFile
 */
const uploadLoading = ref(false)
function beforeAvatarUpload(rawFile, type) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = uploadType[type].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error(
      `上传文件只能是${uploadType[type]
        .toString()
        .replace(/\./g, '')
        .replace(/,/g, '、')}格式!`
    )
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传文件
async function requestFile(params, type) {
  uploadLoading.value = true
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  try {
    let res = await importInvoice(uploadData)
    uploadLoading.value = false
    if (res.code === 200) {
      proxy.$modal.msgSuccess('导入成功')
      uploadDia.value.message = res.msg
      getList()
    }
  } catch (error) {
    uploadLoading.value = false
  }
}

init()
</script>
<style scoped>
:deep(.detailDialog .el-dialog__body) {
  padding: 0 20px !important;
}
</style>
